package com.simon.mctm.biz.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.simon.mctm.base.PageResult;
import com.simon.mctm.biz.sys.bean.User;
import com.simon.mctm.biz.sys.bean.UserDept;
import com.simon.mctm.biz.sys.bean.UserRole;
import com.simon.mctm.biz.sys.dao.UserDeptMapper;
import com.simon.mctm.biz.sys.dao.UserMapper;
import com.simon.mctm.biz.sys.dao.UserRoleMapper;
import com.simon.mctm.biz.sys.dto.UserDto;
import com.simon.mctm.biz.sys.response.UserResponse;
import com.simon.mctm.biz.sys.service.UserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.simon.mctm.exception.OperationFailedException;
import com.simon.mctm.utils.Md5Utils;
import com.simon.mctm.utils.SystemCode;
import com.simon.mctm.utils.Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author simon
 * @since 2018-06-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserDeptMapper userDeptMapper;

    /**
     * 添加用户
     *
     * @param userDto 用户数据传输对象
     * @return 条目数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addUser(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        try {
            //密码MD5加密+salt
            user.setPassword(Md5Utils.getEncryptedPwd(user.getPassword().trim()));
            //创建时间
            user.setCreatetime(new Date());

            return userMapper.insert(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 获取指定用户
     *
     * @param id 用户ID
     * @return 用户数据传输对象
     */
    @Override
    public UserDto getUserById(Integer id) {
        try {
            User user = userMapper.selectById(id);
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            //获取角色id
            userDto.setRoleId(getRoleId(userDto.getId()));
            //获取部门id
            userDto.setDeptId(getDeptId(userDto.getId()));
            return userDto;
        }catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 获取系统用户列表，分页形式
     *
     * @param username 用户名
     * @param status   状态
     * @param pageNum  页码
     * @param pageSize 单页条目数
     * @return 用户列表
     */
    @Override
    public List<UserDto> getUserPagedList(String username, Integer status, Integer pageNum, Integer pageSize) {

        try {
            List<User> userList = userMapper.selectPage(
                    new Page<User>(pageNum, pageSize),
                    new EntityWrapper<User>().like("username", username)
                            .eq("status", status)

            );
            List<UserDto> userResponseList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(userList)) {
                UserDto userDto = null;
                for (User user : userList) {
                    userDto = new UserDto();
                    BeanUtils.copyProperties(user, userDto);
                    userResponseList.add(userDto);
                }
                //获取角色id
                userDto.setRoleId(getRoleId(userDto.getId()));
                //获取部门id
                userDto.setDeptId(getDeptId(userDto.getId()));
            }
            return userResponseList;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getMessage());
        }


    }

    /**
     * 根据新用户更新用户信息
     *
     * @param id 当前用户信息
     * @param newUser 新用户信息
     * @return 影响条目数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateUser(Integer id, UserDto newUser) {
        try {
            User user = new User();
            BeanUtils.copyProperties(newUser,user);
            user.setId(id);
            user.setModifytime(new Date());

            //修改用户角色
            userRoleMapper.delete(
                    new EntityWrapper<UserRole>().eq("sysUserId",id)
            );
            UserRole userRole;
            for (String roleId : newUser.getRoleId().split(",")) {
                userRole = new UserRole(id, new Integer(roleId));
                userRoleMapper.insert(userRole);
            }
            //修改用户部门
            userDeptMapper.delete(
                    new EntityWrapper<UserDept>().eq("sysUserId",id)
            );
            UserDept userDept;
            for (String deptId : newUser.getRoleId().split(",")) {
                userDept = new UserDept(id, new Integer(deptId));
                userDeptMapper.insert(userDept);
            }

            return userMapper.updateUser(user);
        }catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 根据条件获取总条目数和总页数
     *
     * @param username 用户名
     * @param status   状态
     * @param pageSize 单页条目数
     * @return 页数和总条目数对象
     */
    @Override
    public PageResult calPage(String username, Integer status, Integer pageSize) {
        try {
            List<User> userList = userMapper.selectList(
                    new EntityWrapper<User>().like("username", username)
                            .eq("status", status)
            );
            PageResult bPage = new PageResult();
            if (CollectionUtils.isNotEmpty(userList)) {
                bPage.setTotalElements(userList.size());
                bPage.setTotalPage(Utils.calPages(userList.size(), pageSize));
            } else {
                bPage.setTotalElements(0);
                bPage.setTotalPage(0);
            }
            return bPage;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getMessage());
        }
    }

    /**
     * 根据用户名获取用户信息     *
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public User getUserByUsername(String username) {
        try {
            User user = new User();
            user.setUsername(username);
            return userMapper.selectOne(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getMessage());
        }
    }

    /**
     * 通过修改用户状态来删除用户---status：2
     *
     * @param id 用户ID
     * @return 影响条目数
     */
    @Override
    public Integer deleteUser(Integer id) {
        try {
            User user = new User();
            user.setId(id);
            user.setStatus(SystemCode.USER_DELETE);
            user.setModifytime(new Date());
            return userMapper.updateUserStatus(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getMessage());
        }
    }

    /**
     * 修改用户的密码
     *
     * @param user 用户对象
     * @return 影响条目数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer changePassword(User user) {
        try {
            return userMapper.changePassword(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getMessage());
        }
    }

    /**
     * 冻结用户
     *
     * @param user 用户对象
     * @return 影响条目数
     */
    @Override
    public Integer freezeUser(User user) {
        try {
            user.setStatus(SystemCode.USER_FREEZE);
            user.setModifytime(new Date());
            return userMapper.updateStatus(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 取消冻结用户
     *
     * @param user 用户对象
     * @return 影响条目数
     */
    @Override
    public Integer unFreezeUser(User user) {
        try {
            user.setStatus(SystemCode.USER_WORK);
            user.setModifytime(new Date());
            return userMapper.updateStatus(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 设置用户角色
     *
     * @param id      用户Id
     * @param roleIds 角色Id 1,2,3格式
     * @return 影响条目数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer setRoles(Integer id, String roleIds) {
        try {
            //修改用户的角色
            String[] arrRoleIds = roleIds.split(",");
            UserRole userRole = null;
            userRoleMapper.delete(
                    new EntityWrapper<UserRole>().eq("sysUserId",id)
            );
            int res = 0;
            for (String roleId : arrRoleIds) {
                userRole = new UserRole(id, new Integer(roleId));
                res = res + userRoleMapper.insert(userRole);
            }

            return res;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 设置用户部门
     *
     * @param id      用户Id
     * @param deptIds 部门Id 1,2,3格式
     * @return 影响条目数
     */
    @Override
    public Integer setDepts(Integer id, String deptIds) {
        try {
            //修改用户的部门
            String[] arrDeptIds = deptIds.split(",");
            UserDept userDept;
            userDeptMapper.delete(
                    new EntityWrapper<UserDept>().eq("sysUserId",id)
            );
            int res = 0;
            for (String deptId : arrDeptIds) {
                userDept = new UserDept(id, new Integer(deptId));
                res = res + userDeptMapper.insert(userDept);
            }

            return res;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 根据用户Id获取角色id，输出格式为1,2,3
     *
     * @param id 用户Id
     * @return 影响条目数
     */
    @Override
    public String getRoleId(Integer id) {
        try {
            //获取角色
            List<UserRole> userRoles = userRoleMapper.selectList(
                    new EntityWrapper<UserRole>().eq("sysUserId",id)
            );
            StringBuilder sbRole = new StringBuilder();
            if (!userRoles.isEmpty()) {
                for (UserRole userRole : userRoles) {
                    sbRole.append(userRole.getSysRoleId());
                    sbRole.append(",");
                }
                sbRole.deleteCharAt(sbRole.length() - 1);
            }

            return sbRole.toString();
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 根据用户Id获取部门id，输出格式为1,2,3
     *
     * @param id 用户Id
     * @return 影响条目数
     */
    @Override
    public String getDeptId(Integer id) {
        try {
            //获取部门
            List<UserDept> userDepts = userDeptMapper.selectList(
                    new EntityWrapper<UserDept>().eq("sysUserId",id)
            );
            StringBuilder sbDept = new StringBuilder();
            if (!userDepts.isEmpty()) {
                for (UserDept userDept : userDepts) {
                    sbDept.append(userDept.getSysDeptId());
                    sbDept.append(",");
                }
                sbDept.deleteCharAt(sbDept.length() - 1);
            }

            return sbDept.toString();
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }


}
